import React from 'react';
import { Radio, RadioChangeEvent, Space } from 'antd';
import InputFromInterval from './InputFromInterval';
import InputFromTo from './InputFromTo';
import InputSpecified from './InputSpecified';
import InputTarget from './InputTarget';
import { PaneProps, PaneState } from '../data';

/**
 * cron时间表达式生成器-日面板
 * 属性如下：
 */
class DayPane extends React.PureComponent<PaneProps, PaneState> {

  state: PaneState = {
    currentRadio: 0
  }

  /**
   * 静态函数，根据新传入的props来映射到state。
   * 该函数必须有返回值。当props传入的内容不需要影响state，就必须返回一个null
   */
  static getDerivedStateFromProps(nextProps: PaneProps, prevState: PaneState) {
    const { value } = nextProps;
    let currentRadio = 0;
    if (value) {
      if (value === '*') {
        currentRadio = 0;
      } else if (value === '?') {
        currentRadio = 1;
      } else if (value.indexOf('-') > -1) {
        currentRadio = 2;
      } else if (value.indexOf('/') > -1) {
        currentRadio = 3;
      } else if (value.indexOf('W') > -1) {
        currentRadio = 4;
      } else if (value === 'L') {
        currentRadio = 5;
      } else {
        currentRadio = 6;
      }
      return {
        currentRadio
      };
    }
    return null;
  }

  onChangeRadio = (e: RadioChangeEvent) => {
    const valueType = e.target.value;
    this.setState({
      currentRadio: valueType
    });
    const { onChange } = this.props;
    if (onChange) {
      const defaultValues = ['*', '?', '1-1', '1/1', '1W', 'L', '1'];
      onChange(defaultValues[valueType]);
    }
  };

  render() {

    const radioStyle = { lineHeight: '38px' };
    const { value, onChange } = this.props;
    const { currentRadio } = this.state;

    return (
      <Radio.Group style={{ width: '100%' }} value={currentRadio} onChange={this.onChangeRadio}>
        <Space direction='vertical'>
          <Radio style={radioStyle} value={0}>
            每日，允许的通配符 [, - * / L W]
          </Radio>
          <Radio style={radioStyle} value={1}>
            不指定，已设置了周相关配置
          </Radio>
          <Radio style={radioStyle} value={2}>
            <InputFromTo disabled={currentRadio !== 2} value={value} onChange={onChange} />
          </Radio>
          <Radio style={radioStyle} value={3}>
            <InputFromInterval disabled={currentRadio !== 3} value={value} onChange={onChange} />
          </Radio>
          <Radio style={radioStyle} value={4}>
            <InputTarget disabled={currentRadio !== 4} value={value} onChange={onChange} />
          </Radio>
          <Radio style={radioStyle} value={5}>
            本月最后一天执行一次
          </Radio>
          <Radio style={radioStyle} value={6}>
            <InputSpecified disabled={currentRadio !== 6} value={value} onChange={onChange} />
          </Radio>
        </Space>
      </Radio.Group>
    );
  }
}

export default DayPane;